'use strict'
const config = require('config')
const koaTool = require('../../commons/koa_tool')
const admin_auth_service = require('../services/admin_auth')

const _const = require('../../commons/const')
const {
    AdminUserModel,
    UserModel,
    OrderModel,
    MenuModel,
    RoleMenuModel
} = require('../../models/')
const passwordUtility = require('../../commons/password_utility')


module.exports = {
    async test(ctx) {
        let postData = ctx.request.body
        return {
            postData
        }
    },
    async login(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['username', 'password']);
        if (checkError) {
            return koaTool.fail(ctx, checkError);
        }
        let {
            username,
            password,
            captcha_token,
            code
        } = input;
        const cache = require('memory-cache');
        let service_code = cache.get(`captcha_token_${captcha_token}`);
        if(!code || code == undefined || code == ''){
            return koaTool.error(ctx,'验证码错误');
        }
        code = code.toLowerCase();
        if(service_code != code){
            return koaTool.error(ctx,'验证码错误');
        }
        let [loginError, token] = await admin_auth_service.login(username, password);
        if (loginError) {
            console.error(loginError);
            return koaTool.error(ctx, '账号或者密码错误');
        }
        let user = await AdminUserModel.findOne({
            username
        })
        let menuList = [];
        const menuService = require('../services/menu.js');
        if(user.is_super == 2){
            let roleMenuList = await MenuModel.find({'disable':1});
            roleMenuList.map((v) => {
                menuList.push({
                    name:v.name,
                    path:v.path,
                    code:v.code,
                    parent_code:v.parent_code
                })
            })
        }else{
            let roleMenuList = await RoleMenuModel.find({role:user.role}).populate('menu');
            roleMenuList.map((v) => {
                menuList.push({
                    name:v.menu.name,
                    path:v.menu.path,
                    code:v.menu.code,
                    parent_code:v.menu.parent_code
                });
            })
        }
        menuList = menuService.menu_merge(menuList);
        //console.log("menuList:",menuList);
        menuList = menuService.menu_path(menuList);
        //console.log("menuList:",menuList);
        return koaTool.succ(ctx, {
            token,
            menuList
        })
    },

    async appLogin(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['username', 'password']);
        if (checkError) {
            return koaTool.fail(ctx, checkError);
        }

        let {
            username,
            password,
        } = input;
        let [loginError, token] = await admin_auth_service.login(username, password);
        if (loginError) {
            console.error(loginError);
            return koaTool.error(ctx, '账号或者密码错误');
        }
        let user = await AdminUserModel.findOne({
            username
        })
        if(user.is_super == 2){
            return koaTool.error(ctx, '该账号非企业账号');
        }

        return koaTool.succ(ctx, {
            token,
        })
    },


    async logout(ctx) {
        // const data = "success"
        // koaTool.succ(ctx, {
        //     data
        // }, 204)
        koaTool.succ(ctx, {

        }, 204, '退出成功', 204)
    },

    async getUserInfo(ctx) {
        let _user = ctx.state._user;
        _user._ENV_TITLE = config.get('config_name')
        return koaTool.succ(ctx, _user);
    },
    async creatUser(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['username', 'password']);
        if (checkError) {
            return koaTool.fail(ctx, checkError);
        }
        let {
            username,
            password
        } = input;
        const repeatedUser = await UserModel.findOne({
            username
        });
        if (repeatedUser) {
            ctx.throw(409, '用户已经占用');
        }
        let newData = Object.assign({}, input, {
            password: passwordUtility.cookPw(password)
        });
        const result = await UserModel.create(newData)

        return koaTool.succ(ctx, {
            result
        })
    },
    //创建 pc管理员账户
    async createByAdmin(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['username', 'password', 'disable', 'role']);
        if (checkError) {
            return koaTool.fail(ctx, checkError);
        }
        let {
            username,
            password,
            role,
        } = input;
        const adminUser = await AdminUserModel.findOne({
            username
        });
        if (adminUser) {
            ctx.throw(409, '用户已经占用');
        }

        let newData = Object.assign({}, input, {
            password: passwordUtility.cookPw(password)
        });
        const result = await AdminUserModel.create(newData)

        return koaTool.succ(ctx, {
            result
        })
    },
    //获取 PC管理员账户
    async getAdminList(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['page'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let {
            page,
            limit,
        } = ctx.request.query
        console.log('page:', page)
        limit = Number(limit)
        page = page || 0
        page = page - 1
        let query = {
            status: 1,
            username: {$ne: "admin@answer.com"}
        }

        //console.log('user_controller list query', JSON.stringify(query))
        let total = await AdminUserModel.countDocuments(query)
        let list = await AdminUserModel.find(query,'name username role avatar desc create_at').populate({'path':'role',select:'name'}).sort([
            ['_id', -1]
        ]).skip(page * limit).limit(limit)

        console.log("list:", list)
        koaTool.succ(ctx, {
            list,
            total
        })
    },
    //获取 管理员账户信息
    async getAdminInfo(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        try {
            let {
                id
            } = input;
            let obj = {};
            obj._id = id;
            const detail = await AdminUserModel.findById(obj);
            koaTool.succ(ctx, {
                detail
            })
        } catch (error) {
            return koaTool.succ(ctx, {}, 405, `${error}`)
        }
    },
    //更新 管理员账号信息]
    async updateAdminInfo(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        const {
            username,
            password,
            disable,
            role,
            bu,
            desc
        } = input
        let adminUser = await AdminUserModel.findById(input.id)
        //查询到 Admin 用户信息
        if (!adminUser) {
            ctx.throw(404, '用户不存在')
        }

        let propList = ["username","disable","role","desc","name"];
        propList.forEach(prop => {
            if(input[prop]){
                adminUser[[prop]] = input[prop]
            }
        })

        if (input.password) {
            adminUser.password = passwordUtility.cookPw(input.password);
        }
        
        await adminUser.save()
        koaTool.succ(ctx, {
            adminUser
        })
    },
    //删除 admin 用户信息
    async delAdminUser(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, ['id'])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        // await AdminUserModel.findByIdAndRemove(input.id)
        let adminUser = await AdminUserModel.findById(input.id);
        adminUser.state = 2;
        await adminUser.save();
        koaTool.succ(ctx, {
            msg: '成功'
        })
    },
    async count(ctx) {
        let query = {}
        let users = await UserModel.countDocuments(query)
        let topics = await OrderModel.countDocuments(query)

        return koaTool.succ(ctx, {
            users,
            topics,
        })
    },
    async GetCaptcha(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let captchaService = require('../services/captcha.js');
        const captcha = await captchaService.getCaptcha();
        const cache = require('memory-cache')
        const {getUuidCode} = require('../../commons/util.js');
        let captcha_token = getUuidCode();
        cache.put(`captcha_token_${captcha_token}`, captcha.text.toLowerCase(),  120000);  //加入缓存
        return koaTool.success(ctx,'获取成功',{
            captcha_token,
            img: captcha.data
        });
        // ctx.response.token = captcha_token;
        // //设置响应头
        // ctx.response.type = "image/svg+xml";

        // ctx.body = captcha.data;
    },
    async changePass(ctx) {
        let [checkError, input] = koaTool.checkInput(ctx, [])
        if (checkError) {
            return koaTool.fail(ctx, checkError)
        }
        let {
            password
        } = input;
        let adminId = ctx.state._user_id;
        console.log("adminId:",ctx.state);
        let {isNull} = require('../../commons/util.js');
        let adminUser = await AdminUserModel.findById(adminId);
        //查询到 Admin 用户信息
        if (!adminUser) {
            ctx.throw(404, '用户不存在')
        }

        if(isNull(password)){
            return koaTool.error(ctx,"密码不能为空")
        }

        adminUser.password = passwordUtility.cookPw(password);
        await adminUser.save();

        return koaTool.success(ctx,"修改成功");
    }

}